from random import randint

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from . import constants
from .serializer import RegisterSmsCodeSerializer
from rest_framework.response import Response
from rest_framework import status
# from libs.yuntongxun


class RegisterImageCodeView(APIView):

    def get(self, request, image_code_id):

        # 1.生成验证码和图片
        text, image = captcha.generate_captcha()

        # 2.链接redis
        redis_conn = get_redis_connection('code')

        # 3.保存uuid到redis
        redis_conn.setex('img_%s' % image_code_id, 200, text)

        # 4.返回图片
        return HttpResponse(image, content_type='image/jpeg')



class RegisterSmsCode(GenericAPIView):

    serializer_class = RegisterSmsCodeSerializer

    def get(self, request, mobile):

        # 1.创建序列化器
        serializer = self.get_serializer(data=request.query_params)

        # 2.校验数据
        serializer.is_valid(raise_exception=True)

        # 3.链接redis
        redis_conn = get_redis_connection('code')

        # 4.先判断用户的这个手机号之前是否发送过短信
        if redis_conn.get('sms_flag_%s' % mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)

        # 5.生成短信验证码
        sms_code = '%06d' % randint(0, 999999)

        # 6.redis增加记录
        redis_conn.setex('sms_%s' % mobile, 5*60, sms_code)
        redis_conn.setex('sms_flag_%s' % mobile, 60, 1)
        #
        # # 7.发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)

        from celery_tasks.sms.tasks import send_msm_code
        send_msm_code.delay(mobile, sms_code)

        # 8.返回响应
        return Response({'message': 'ok'})
